package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Appointment;
import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.AppointmentMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.AppointmentQuery;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoServicePlus;
import cn.wolfcode.car.business.service.ICarPackageAuditServicePlus;
import cn.wolfcode.car.business.service.IServiceItemServicePlus;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImplPlus extends ServiceImpl<CarPackageAuditMapper, CarPackageAudit> implements ICarPackageAuditServicePlus {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IBpmnInfoServicePlus bpmnInfoServicePlus;
    @Autowired
    private IServiceItemServicePlus serviceItemServicePlus;
    @Autowired
    private TaskService taskService;

    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        IPage<CarPackageAudit> page = new Page<>(qo.getPageNum(),qo.getPageSize());
        QueryWrapper<CarPackageAudit> wrapper = new QueryWrapper<>();
        wrapper.ge(qo.getBeginTime() != null,"create_time", qo.getBeginTime())
                .le(qo.getEndTime() != null,"create_time",qo.getEndTime())
                .eq(qo.getAuditorId() != null,"auditor_id",qo.getAuditorId())
                .eq(qo.getStatus() != null,"status",qo.getStatus())
                .like(StringUtils.hasText(qo.getInfo()),"info", qo.getInfo());
        return new TablePageInfo<CarPackageAudit>(super.page(page,wrapper));
    }

    @Override
    public InputStream getProcessImgAsStream(Long id) {
        //通过id获取审核记录对象的状态
        CarPackageAudit audit = carPackageAuditMapper.selectById(id);
        String instanceId = audit.getInstanceId();
        List<String> highLightedActivities = null;
        if(CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())){
            //获取流程实例对象
            //如果是处于审核中，需要高亮目前运行的节点
            //通过流程实例id获取到目前活动节点
            highLightedActivities = runtimeService.getActiveActivityIds(instanceId);
        }else{
            //如果是审核拒绝或审核通过，就不需要进行高亮
            highLightedActivities = new ArrayList<>();
        }
        //获取流程定义id,通过id获取BpmnModel对象
        BpmnInfo bpmnInfo = bpmnInfoServicePlus.getById(audit.getBpmnInfoId());
        BpmnModel bpmnModel = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        return generator.generateDiagram(bpmnModel,highLightedActivities, Collections.EMPTY_LIST,"宋体","宋体","宋体");
    }

    @Override
    public void cancelApply(Long id) {
        CarPackageAudit audit = carPackageAuditMapper.selectById(id);
        if(!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())){
            throw new BusinessException("只有处于审核中的审核记录才运行删除");
        }
        //将服务单项的审核状态修改为初始化
        Long serviceItemId = audit.getServiceItemId();
        UpdateWrapper<ServiceItem> wrapper1 = new UpdateWrapper<>();
        wrapper1.eq("id",serviceItemId)
                .set("audit_status",ServiceItem.AUDITSTATUS_INIT);
        serviceItemServicePlus.update(null,wrapper1);

        //删除流程实例
        runtimeService.deleteProcessInstance(audit.getInstanceId(),"撤销审核");
        //将审核对象的状态修改为已撤销
        UpdateWrapper<CarPackageAudit> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",id)
                .set("status",CarPackageAudit.STATUS_CANCEL);
        carPackageAuditMapper.update(null,wrapper);
    }

    @Override
    @Transactional
    public void audit(Long id, Integer auditStatus, String info) {
        //进行合理性效验
        //CarPackageAudit audit = this.get(id);
        CarPackageAudit audit = carPackageAuditMapper.selectById(id);
        //流程处于审核中才可以进行审核
        if(audit == null || !CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())){
            throw new BusinessException("流程处于审核中才可以进行审核");
        }
        //只有处理人才可以对该审核记录进行审核
        if(!ShiroUtils.getUserId().equals(audit.getAuditorId())){
            throw new BusinessException("只有处理人才可以对该审核记录进行审核");
        }
        String userName = ShiroUtils.getUser().getUserName();
        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            //同意
            info = "[" + userName + "]同意，审批意见：" + info;
        }else {
            //拒绝
            info = "[" + userName + "]拒绝，审批意见：" + info;
        }
        //将审核意见存储到info信息中
        audit.setInfo(audit.getInfo() + "</br>" + info);
        //让流程往后流转，完成任务前需设置流程变量，是通过还是拒绝
        Task task = taskService.createTaskQuery().processInstanceId(audit.getInstanceId())
                .singleResult();
        taskService.setVariable(task.getId(),"auditStatus",auditStatus);
        //添加审批备注
        taskService.addComment(task.getId(),audit.getInstanceId(),info);
        taskService.complete(task.getId());

        //不管通过还是拒绝都需要审核
        audit.setAuditTime(new Date());

        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            //通过
            //判断是否还有下一个节点
            Task nextTask = taskService.createTaskQuery().processInstanceId(audit.getInstanceId())
                    .singleResult();
            if(nextTask != null){
                //有下一个节点
                audit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
            }else{
                //没有下一个节点了，流程走完了，更改审核对象的状态为审核通过，更改服务单项的状态为审核通过
                audit.setStatus(CarPackageAudit.STATUS_PASS);
                //serviceItemServicePlus.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
                UpdateWrapper<ServiceItem> wrapper = new UpdateWrapper<>();
                wrapper.eq("id",audit.getServiceItemId())
                        .set("audit_status",ServiceItem.AUDITSTATUS_APPROVED);
                serviceItemServicePlus.update(null,wrapper);
            }
        }else{
            //拒绝
            //审核对象的状态改为审核拒绝
            audit.setStatus(CarPackageAudit.STATUS_REJECT);
            //服务单项的状态改为初始化
            //serviceItemServicePlus.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
            UpdateWrapper<ServiceItem> wrapper = new UpdateWrapper<>();
            wrapper.eq("id",audit.getServiceItemId())
                    .set("audit_status",ServiceItem.AUDITSTATUS_INIT);
            serviceItemServicePlus.update(null,wrapper);
        }
        //carPackageAuditMapper.updateByPrimaryKey(audit);
        carPackageAuditMapper.updateById(audit);
    }
}
